import { type Layer } from "ol/layer";

const mapData = {
	center: [],
	rotation: 0,
	offsetX: 0,
	offsetY: 0,
	pixelScale: 0,
};

// 操作canvas实现地图裁剪
function ininClip(layer: Layer, geom: any) {
	// 图层渲染前触发，ev为渲染事件对象
	layer.on("prerender", (ev) => {
		let coords: any = [];
		// highlight.getGeometry().getCoordinates()获取几何图形各个点坐标
		geom.forEach((highlight: any) => {
			coords = [...coords, ...highlight.getGeometry().getCoordinates()];
		});
		// geom[0].getGeometry().getType() 获取几何图形的类型
		clip(ev, geom[0].getGeometry().getType(), coords);
	});
	// 图层渲染后触发，event为渲染事件对象
	layer.on("postrender", function (event: any) {
		// 获取图形上下文对象CanvasRenderingContext2D
		const ctx = event.context;
		// 恢复之前保存的绘图状态，restore调用次数应小于或等于save保存绘图状态的次数
		ctx.restore();
	});
}
function clip(evt: any, type: string, coords: string | any[]) {
	// 获取图形上下文对象CanvasRenderingContext2D
	const canvas = evt.context;
	// 保存绘图状态
	canvas.save();
	//  let coords = highlight.getGeometry().getCoordinates();
	// 获取地图状态
	const frameState = evt.frameState;
	// 获取像素比
	const pixelRatio = frameState.pixelRatio;
	// 获取视图状态
	const viewState = frameState.viewState;
	// 获取视图中心点
	mapData.center = viewState.center;
	// 获取视图的分辨率
	const resolution = viewState.resolution;
	// 获取视图旋转角度
	mapData.rotation = viewState.rotation;
	// 获取地图的大小
	const size = frameState.size;
	// const size1 = Map.getSize()
	mapData.offsetX = Math.round((pixelRatio * size[0]) / 2);
	mapData.offsetY = Math.round((pixelRatio * size[1]) / 2);
	mapData.pixelScale = pixelRatio / resolution;
	// 开启新的路径或重置当前路径
	canvas.beginPath();
	if (type === "MultiPolygon") {
		for (let i = 0; i < coords.length; i++) {
			createClip(coords[i][0], canvas);
		}
	} else if (type === "Polygon") {
		createClip(coords[0], canvas);
	}
	canvas.clip();
}
function createClip(coords: any, canvas: any) {
	const { offsetX, offsetY, pixelScale, center, rotation } = mapData;
	for (let i = 0, cout = coords.length; i < cout; i++) {
		const xLen = Math.round((coords[i][0] - center[0]) * pixelScale);
		const yLen = Math.round((center[1] - coords[i][1]) * pixelScale);
		let x = offsetX;
		let y = offsetY;
		if (rotation !== 0) {
			x = xLen * Math.cos(rotation) - yLen * Math.sin(rotation) + offsetX;
			y = xLen * Math.sin(rotation) + yLen * Math.cos(rotation) + offsetY;
		} else {
			x = xLen + offsetX;
			y = yLen + offsetY;
		}
		if (i === 0) {
			// 移动到绘制的起点
			canvas.moveTo(x, y);
		} else {
			// 线状连接点
			canvas.lineTo(x, y);
		}
	}
	canvas.closePath();
	// canvas.strokeStyle = '#30A8C1'
	// canvas.stroke()
}

export default ininClip;
